import pGouwuche from '@/mainSubPack/images/takeOutShop/gouwuche.png';
import utils from '@/utils';
import { Image, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import React, { useCallback, useEffect } from 'react';
import { connect } from 'react-redux';
import './index.scss';

const goCartPage = () => {
  if (!utils.getToken()) {
    Taro.navigateTo({
      url: '/pages/other/login/index',
    });
    return;
  }

  let url = '/pages/mainPages/cartSin/index';
  Taro.navigateTo({ url });
};

const RightBottomCart = ({ dispatch, productNumInCart }) => {
  const getProductTotalNum = useCallback(() => {
    dispatch({
      type: 'productList/getProductTotalNum',
      payload: {  type: 1 },
    });
  }, []);

  useDidShow(() => {
    Taro.verifyLogin()
    getProductTotalNum();
  });

  // 离开页面, 清空数据
  useEffect(() => {
    return () => {
      dispatch({
        type: 'productList/setProductTotalNum',
        payload: { productNumInCart: null },
      });
    };
  }, []);

  return (
    <View className="RightBottomCart">
      <Image className="gwcImg" src={pGouwuche} onClick={goCartPage} />
      {productNumInCart && productNumInCart > 0 && (
        <View
          className={[
            'gwcNum',
            productNumInCart > 9 && 'two',
            productNumInCart > 99 && 'three',
          ].join(' ')}
        >
          {productNumInCart > 99 ? '99+' : productNumInCart}
        </View>
      )}
    </View>
  );
};

export default connect(({ productList }) => ({
  productNumInCart: productList.productNumInCart,
}))(RightBottomCart);
